//
//  NSObject+Extension.m
//  DEMO
//
//  Created by J on 16/2/24.
//  Copyright © 2016年 J. All rights reserved.
//

#import "NSObject+Extension.h"

@implementation NSObject (Extension)

- (id)performSelector:(SEL)selector withObjects:(NSArray*)objects{
    
    //方法的描述
    NSMethodSignature* ges = [self.class instanceMethodSignatureForSelector:selector];
    if (!ges) {
        //真实开发是闪退
//       @throw [NSException exceptionWithName:@"方法找不到" reason:@"方法找不到" userInfo:nil];
        
//        [NSException raise:@"方法找不到" format:@"%@方法找不到",NSStringFromSelector(selector) ];
        return nil;
    }
    NSInvocation * invocation = [NSInvocation invocationWithMethodSignature:ges];
    invocation.target = self;
    invocation.selector = selector;
    //设置参数
//    NSString* num = @"10086";
    NSUInteger count = ges.numberOfArguments-2;//去除self and _cmd自带的2个参数
    count = MIN(count, objects.count);//取最小值
    for (NSInteger i = 0; i<count; i++) {
        id objc = objects[i];
        if ([objc isKindOfClass:[NSNull class]]) {
            continue;
        }
        [invocation setArgument:&objc atIndex:i+2];//设置参数
    }
    

    
    [invocation invoke];//执行
    
    id returnValue = nil;
    if (ges.methodReturnLength) {//返回值不为void才去获得返回值类型
        [invocation getReturnValue:&returnValue];
    }
    return  returnValue;
 
}
@end
